package com.mingmen.supplier.activity;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.imagepicker.ImagePicker;
import com.mingmen.supplier.R;
import com.mingmen.supplier.adapter.CommodityAllAdapter;
import com.mingmen.supplier.adapter.CommodityRightAdapter;
import com.mingmen.supplier.adapter.CommodityShopAdapter;
import com.mingmen.supplier.base.BaseBean;
import com.mingmen.supplier.http.callback.StringCallback;
import com.mingmen.supplier.httpconfig.HttpResponse;
import com.mingmen.supplier.immersionbar.ImmersionBar;
import com.mingmen.supplier.model.CommodityAllModel;
import com.mingmen.supplier.model.CommodityRightModel;
import com.mingmen.supplier.model.ShopManageModel;
import com.mingmen.supplier.popwindow.PopupWindowCompat;
import com.mingmen.supplier.refresh.ClassicsFooter;
import com.mingmen.supplier.refresh.ClassicsHeader;
import com.mingmen.supplier.util.GsonUtil;
import com.mingmen.supplier.util.MyStringUtils;
import com.mingmen.supplier.util.SharePreferenceUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

public class CommodityShopActivity extends AppCompatActivity implements CommodityShopAdapter.OnItemClickListener {

    //返回按钮
    @BindView(R.id.text_return)
    TextView textReturn;

    private ImagePicker imagePicker;

    @BindView(R.id.btn_login)
    Button btn_login;

    private int resurtResurant = 100;
    @BindView(R.id.recycle_shopo)
    RecyclerView mRecyclerView;

    CommodityShopAdapter commodityAdapter;


    LinearLayoutManager linearLayoutManager;
    @BindView(R.id.img_jingying)
    ImageView img_jingying;
    @BindView(R.id.img_shangjia)
    ImageView img_shangjia;

    PopupWindowCompat popupWindow;
    @BindView(R.id.view_dishline)
    View view_dishline;
    @BindView(R.id.layout_pinlei)
    LinearLayout layout_pinlei;
    CommodityAllAdapter commodityLabelAdapter;
    private List<CommodityAllModel.DataBean> mListData = new ArrayList<>();
    @BindView(R.id.layout_xiajia)
    LinearLayout layout_xiajia;
    @BindView(R.id.btn_auditlist)
    Button btn_auditlist;
    String token;
    List<ShopManageModel.DataBean> dataBeanList = new ArrayList<>();
    @BindView(R.id.linear_return)
    LinearLayout linear_return;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;
    Bitmap bitmap;
    List<String> jdataData = new ArrayList<>();
    String categoryId = "";
    String state = "0";
    String keyword;
    @BindView(R.id.text_allCategory)
    TextView text_allCategory;

    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    int pageNumber = 1;
    int totalPage;
    @BindView(R.id.layout_alldata)
    LinearLayout layout_alldata;
    @BindView(R.id.text_shangjia)
    TextView text_shangjia;
    List<String> commodityIds = new ArrayList<>();
    String flag = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity);
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .init();
        EventBus.getDefault().register(this);
        linearLayoutManager = new LinearLayoutManager(this);
        token = (String) SharePreferenceUtil.get(this, "token", "");
        popWindowCreate();

        Log.d("tokentoken", token);

        mRecyclerView.setLayoutManager(linearLayoutManager);
        commodityAdapter = new CommodityShopAdapter(this, dataBeanList);
        mRecyclerView.setAdapter(commodityAdapter);
        commodityAdapter.setOnItemClickListener(this);


        commodityAdapter.setOnItemClickListener(this);
        getData(token, categoryId, state, keyword, pageNumber);
        refreshLayout.setRefreshHeader(new ClassicsHeader(CommodityShopActivity.this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(CommodityShopActivity.this));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                dataBeanList.clear();
                pageNumber = 1;
//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                getData(token, categoryId, state, keyword, pageNumber);
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (pageNumber >= totalPage) {
                    Toast.makeText(CommodityShopActivity.this, "已到最后一页", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishLoadMore(false);//传入false表示加载失败
                } else {
//                    pageNumber++;
//                    getData(token, categoryId, state, keyword, pageNumber);
                    HttpResponse.getSupplierCommodity(token, categoryId, state, keyword, pageNumber, new StringCallback(CommodityShopActivity.this) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            BaseBean baseBean = new BaseBean();
                            baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                            if (commodityIds.size() > 0) {
                                commodityIds.clear();
                            }
                            if (dataBeanList.size() > 0) {
                                dataBeanList.clear();
                            }
                            if (baseBean.getCode() == 0) {

                                ShopManageModel shopManageModel = new ShopManageModel();
                                shopManageModel = GsonUtil.GsonToBean(s, ShopManageModel.class);
                                dataBeanList.addAll(shopManageModel.getData());
                                for (int i = 0; i < dataBeanList.size(); i++) {
                                    commodityIds.add(dataBeanList.get(i).getCommodityId());
                                }
                                if (dataBeanList.size() == 0) {
                                    layout_nodata.setVisibility(View.VISIBLE);
                                    layout_alldata.setVisibility(View.GONE);
                                } else {
                                    layout_nodata.setVisibility(View.GONE);
                                    layout_alldata.setVisibility(View.VISIBLE);
                                }
                                totalPage = shopManageModel.getTotalPage();
                                commodityAdapter.setDataList(dataBeanList);
                            }
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            if (dataBeanList.size() == 0) {
                                layout_nodata.setVisibility(View.VISIBLE);
                            }
                        }

                        @Override
                        public void onAfter(String s, Exception e) {
                            super.onAfter(s, e);
                            refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                            refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                        }
                    });
                    refreshlayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                }


            }
        });
        img_shangjia.setRotation(180);
        img_jingying.setRotation(180);
    }

    public void getData(String token, String categoryId, String state, String keyword, int pageNumber) {
        HttpResponse.getSupplierCommodity(token, categoryId, state, keyword, pageNumber, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (commodityIds.size() > 0) {
                    commodityIds.clear();
                }
                if (dataBeanList.size() > 0) {
                    dataBeanList.clear();
                }

                if (baseBean.getCode() == 0) {

                    ShopManageModel shopManageModel = new ShopManageModel();
                    shopManageModel = GsonUtil.GsonToBean(s, ShopManageModel.class);
                    dataBeanList.addAll(shopManageModel.getData());
                    for (int i = 0; i < dataBeanList.size(); i++) {
                        commodityIds.add(dataBeanList.get(i).getCommodityId());
                    }
                    if (dataBeanList.size() > 0) {
                        if (dataBeanList.get(0).getState().equals("2")) {
                            text_shangjia.setText("下架");
                        } else if (dataBeanList.get(0).getState().equals("3")) {
                            text_shangjia.setText("上架");

                        }
                    }


                    if (dataBeanList.size() == 0) {
                        layout_nodata.setVisibility(View.VISIBLE);
                        layout_alldata.setVisibility(View.GONE);
                    } else {
                        layout_nodata.setVisibility(View.GONE);
                        layout_alldata.setVisibility(View.VISIBLE);
                    }
                    totalPage = shopManageModel.getTotalPage();
                    commodityAdapter.setDataList(dataBeanList);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                if (dataBeanList.size() == 0) {
                    layout_nodata.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onAfter(String s, Exception e) {
                super.onAfter(s, e);
                refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
            }
        });
    }


    @OnClick({R.id.text_return, R.id.btn_login, R.id.layout_pinlei, R.id.layout_xiajia, R.id.btn_auditlist, R.id.linear_return, R.id.text_shangjia})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_return:
                finish();
                break;
            case R.id.btn_login:
                startActivity(new Intent(CommodityShopActivity.this, CommodityShopManagerActivity.class));

                break;
            case R.id.layout_pinlei:
          /*      img_jingying.setImageResource(R.mipmap.arrowblue_bottom);
                img_jingying.setRotation(180);*/
//                img_shangjia.setRotation(180);
//                img_jingying.setRotation(180);
                img_shangjia.setRotation(360);
                img_jingying.setRotation(360);
                img_jingying.setImageResource(R.mipmap.arrowblue_bottom);
                img_shangjia.setImageResource(R.mipmap.arrowblue_bottom);
                popupWindow.showAsDropDown(view_dishline);

                break;
            case R.id.layout_xiajia:
//                img_shangjia.setImageResource(R.mipmap.arrowblue_bottom);
//                img_shangjia.setRotation(180);
//                img_shangjia.setRotation(180);
//                img_jingying.setRotation(180);
                img_shangjia.setRotation(360);
                img_jingying.setRotation(360);
                popupWindow.showAsDropDown(view_dishline);
                img_shangjia.setImageResource(R.mipmap.arrowblue_bottom);
                break;
            case R.id.btn_auditlist:
                startActivity(new Intent(CommodityShopActivity.this, AuditListActivity.class));
                break;
            case R.id.linear_return:
                finish();
                break;
            case R.id.text_shangjia:


                /*   String commodityIdList = MyStringUtils.returnStringBuffer(commodityIds);
                if (text_shangjia.getText().toString().equals("上架")) {
                    addShop(token, commodityIdList);
                } else {
                    HttpResponse.stopSupplierCommodity(token, commodityIdList, new StringCallback(CommodityShopActivity.this) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            BaseBean baseBean = new BaseBean();
                            baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                            if (baseBean.getCode() == 0) {
                                dataBeanList.clear();
                                getData(token, categoryId, state, keyword, pageNumber);
                            }
                            Toast.makeText(CommodityShopActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
*/

                break;
        }
    }


    public void popWindowCreate() {
//        CommodityFragment
        popupWindow = new PopupWindowCompat(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_commodity, null);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setContentView(contentView);
//        popupWindow.setOutsideTouchable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        TextView textView = contentView.findViewById(R.id.tv_kdd);
        textView.setText("");
        LinearLayout layout_content = contentView.findViewById(R.id.layout_content);
        layout_content.getBackground().setAlpha(180);
        RecyclerView recyclerView = contentView.findViewById(R.id.recycler_view);
        RecyclerView recycler_right = contentView.findViewById(R.id.recycler_right);


        GridLayoutManager gridLayoutManager = new GridLayoutManager(CommodityShopActivity.this, 3);
//        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        DividerItemDecoration divider = new DividerItemDecoration(CommodityShopActivity.this, DividerItemDecoration.VERTICAL);
        recycler_right.setLayoutManager(new LinearLayoutManager(this));
        divider.setDrawable(ContextCompat.getDrawable(CommodityShopActivity.this, R.drawable.custom_divider));
//        recyclerView.addItemDecoration(divider);
        commodityLabelAdapter = new CommodityAllAdapter(CommodityShopActivity.this, mListData);
        recyclerView.setAdapter(commodityLabelAdapter);
        List<CommodityRightModel.ChildrenBean> childrenBeanList = new ArrayList<>();

        CommodityRightAdapter commodityRightAdapter = new CommodityRightAdapter(CommodityShopActivity.this, childrenBeanList);
        recycler_right.setAdapter(commodityRightAdapter);
        List<CommodityAllModel.DataBean> mListData2 = new ArrayList<>();
        HttpResponse.getCategoryList(token, "0", "0", new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                Log.d("getCategoryList", s);

                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    CommodityAllModel commodityAllModel = new CommodityAllModel();
                    commodityAllModel = GsonUtil.GsonToBean(s, CommodityAllModel.class);

                    List<CommodityAllModel.DataBean.ChildrenBean> childrenBeans = new ArrayList<>();
                    for (int i = 0; i < commodityAllModel.getData().size(); i++) {
                        for (int j = 0; j < commodityAllModel.getData().get(i).getChildren().size(); j++) {
                            CommodityAllModel.DataBean.ChildrenBean dataBean = new CommodityAllModel.DataBean.ChildrenBean();
                            dataBean.setCategoryName(commodityAllModel.getData().get(j).getCategoryName());
                            dataBean.setParentId(commodityAllModel.getData().get(j).getParentId());
                            dataBean.setHavaChildren(commodityAllModel.getData().get(j).getHavaChildren());
                            childrenBeans.add(dataBean);
                        }
                    }

                    CommodityAllModel.DataBean dataBean1 = new CommodityAllModel.DataBean();
                    dataBean1.setCategoryName("全部");
                    dataBean1.setParentId("666");
                    dataBean1.setCategoryId("0");
                    dataBean1.setHavaChildren(0);
                    dataBean1.setChildren(childrenBeans);

                    mListData.add(dataBean1);
                    mListData.addAll(commodityAllModel.getData());
                    commodityLabelAdapter.update(mListData);
                    Log.d("beanToString", MyStringUtils.beanToString(mListData.get(0)));
                    CommodityRightModel commodityRightModel = new CommodityRightModel();
                    commodityRightModel = GsonUtil.GsonToBean(MyStringUtils.beanToString(mListData.get(0)), CommodityRightModel.class);
                    childrenBeanList.addAll(commodityRightModel.getChildren());
                    commodityRightAdapter.update(childrenBeanList);
                } else {
                    startActivity(new Intent(CommodityShopActivity.this, LoginActivity.class));
                    Toast.makeText(CommodityShopActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                    finish();

                }


            }
        });
        commodityLabelAdapter.setOnItemClickListener(new CommodityAllAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position, List<CommodityAllModel.DataBean> mListData) {
                commodityLabelAdapter.setCheckedPosition(position);
                if (childrenBeanList.size() > 0) {
                    childrenBeanList.clear();
                }
                if (position == 0) {
                    text_allCategory.setText("全部分类");
                    getData(token, "", "0", "", 1);

                    img_jingying.setImageResource(R.mipmap.arrowblue_bottom);
                    img_shangjia.setImageResource(R.mipmap.arrowblue_bottom);
                    img_shangjia.setRotation(180);
                    img_jingying.setRotation(180);
                    popupWindow.dismiss();
                }

                commodityRightAdapter.setCheckedPosition(position);
                Log.d("CommodityCommodity", MyStringUtils.beanToString(mListData.get(position)));
                CommodityRightModel commodityRightModel = new CommodityRightModel();
                commodityRightModel = GsonUtil.GsonToBean(MyStringUtils.beanToString(mListData.get(position)), CommodityRightModel.class);
                childrenBeanList.addAll(commodityRightModel.getChildren());
                commodityRightAdapter.update(childrenBeanList);
            }
        });
        commodityRightAdapter.setOnItemClickListener(new CommodityRightAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position, List<CommodityRightModel.ChildrenBean> mListData) {
                popupWindow.dismiss();

                img_jingying.setImageResource(R.mipmap.arrowblue_bottom);
                img_shangjia.setImageResource(R.mipmap.arrowblue_bottom);
                img_shangjia.setRotation(180);
                img_jingying.setRotation(180);
                commodityRightAdapter.setCheckedPosition(position);

                dataBeanList.clear();
                getData(token, mListData.get(position).getCategoryId(), state, "", 1);
                text_allCategory.setText(mListData.get(position).getCategoryName());
            }
        });

    }


    @Override
    public void onItemClickListener(View view, int pos, List<ShopManageModel.DataBean> myLiveList) {
        Intent intent;

        switch (view.getId()) {
            case R.id.text_manager:
                JSONObject jsonObject = new JSONObject();
                if (jdataData.isEmpty()) {
                    jdataData.clear();
                }
                try {
                    jsonObject.put("commodityId", myLiveList.get(pos).getCommodityId());
                    jsonObject.put("price", myLiveList.get(pos).getPrice() + "");
                    jsonObject.put("amount", "0");
                    jsonObject.put("state", myLiveList.get(pos).getState());

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                jdataData.add(jsonObject.toString());

                intent = new Intent(CommodityShopActivity.this, WeiHuListActivity.class);
//                intent.putExtra("categoryId", myLiveList.get(pos).getCategoryId());
//                intent.putExtra("jdataData", jdataData.toString());
                startActivity(intent);

                break;
            case R.id.state:
                if (myLiveList.get(pos).getState().equals("2")) {
                    HttpResponse.stopSupplierCommodity(token, myLiveList.get(pos).getCommodityId(), new StringCallback(CommodityShopActivity.this) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            BaseBean baseBean = new BaseBean();
                            baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                            if (baseBean.getCode() == 0) {
                                dataBeanList.clear();
                                getData(token, categoryId, state, keyword, pageNumber);
                            }
                            Toast.makeText(CommodityShopActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    addShop(token, myLiveList.get(pos).getCommodityId());
                }


                break;
            default:
                intent = new Intent(CommodityShopActivity.this, AuditDetailActivity.class);
                Log.d("commodityIdcommodityId", myLiveList.get(pos).getCommodityId() + "");
//                        CommodityShopManagerActivity
                intent.putExtra("commodityId", myLiveList.get(pos).getCommodityId() + "");
                startActivity(intent);

        }
    }

    public void onEventMainThread(Integer integer) {
        if (integer == 11) {

            dataBeanList.clear();
            getData(token, "", state, keyword, 1);
        }

    }

    public void addShop(String token, String commodityIds) {

        HttpResponse.setCommodityFromLibrary(token, commodityIds, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                Toast.makeText(CommodityShopActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                if (baseBean.getCode() == 0) {

                    getData(token, "", state, keyword, 1);
                }
            }
        });
    }
}




